//
//  YJCaiPersonVC.m
//  YJB
//
//  Created by 高卫明 on 16/5/27.
//  Copyright © 2016年 YJB. All rights reserved.
//

#import "THPersonVC.h"
#import "THPersonData.h"
#import "THPersonTableViewHeaderView.h"
#import "ReactiveCocoa.h"
#import "THMineWalletMainViewController.h" //我的钱包
#import "THVipTopUpViewController.h"       //VIP升级
#import "THRMBExchangeViewController.h"    //兑换
#import "THMyInfoViewController.h"

#define kTHPersonTableViewHeaderHeight DiffValue(160, 140)

@interface THPersonVC ()<UITableViewDelegate, UITableViewDataSource>
@property(nonatomic,strong)NSMutableArray *datas;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) THPersonTableViewHeaderView *headerView;

@property (nonatomic, copy)   NSString *username;
@property (nonatomic, copy)   NSString *avatarIcon;
@property (nonatomic, strong) NSDictionary *vipInfo;
@property (nonatomic, copy)   NSString *moneyCount;
@property (nonatomic, copy)   NSString *goldCount;
@end


@implementation THPersonVC
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeTop;
    [self.view addSubview:self.tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(-20, 0, 0, 0));
    }];
    [self getInfo];
}


- (void)viewDidLayoutSubviews {
    self.headerView.height = kTHPersonTableViewHeaderHeight;
}

 
-(NSMutableArray *)datas
{
    if (_datas == nil)
    {
        _datas = [NSMutableArray array];
        NSString *path = [[NSBundle mainBundle]pathForResource:@"personList.plist" ofType:nil];
        NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
        for (NSArray *array in dict[@"person"])
        {
         NSArray *arrayModel = [THPersonData personsWithArray:array];
        [_datas addObject:arrayModel];
        }
    }
    return _datas;
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.datas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = self.datas[section];
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *personID = @"personCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:personID];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:personID];
        cell.textLabel.font = [UIFont systemFontOfSize:17.0f];
        cell.textLabel.textColor = kUIColorFromRGB(0x414141);

    }
    //取出模型数据
    NSArray *persons = self.datas[indexPath.section];
    THPersonData *person = persons[indexPath.row];
    cell.textLabel.text = person.title;
    cell.imageView.image = [UIImage imageNamed:person.image];
    return cell;
}

 

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 12;
}

- (CGFloat )tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [UIView new];
    headerView.backgroundColor = [UIColor clearColor];
    return headerView;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSArray *persons = self.datas[indexPath.section];
    THPersonData *person = persons[indexPath.row];
    Class class = NSClassFromString(person.vct);
    
    //我的钱包
    if ([person.vct isEqualToString:@"THMineWalletMainViewController"]) {
        THMineWalletMainViewController *vct = (THMineWalletMainViewController*)[[class alloc] init];
        vct.goleCount = self.goldCount;
        vct.moneyCount = self.moneyCount;
        [self.navigationController pushViewController:vct animated:YES];
    }
    //vip充值
    else if ([person.vct isEqualToString:@"THVipTopUpViewController"]) {
        THVipTopUpViewController *vct = (THVipTopUpViewController*)[[class alloc] init];
        vct.delegate = [RACSubject subject];
        [vct.delegate subscribeNext:^(NSDictionary *x) {
            [self getInfo];
        }];
        [self.navigationController pushViewController:vct animated:YES];
    }else if ([person.vct isEqualToString:@"THRMBExchangeViewController"]){
        THRMBExchangeViewController *vct = (THRMBExchangeViewController*)[[class alloc] init];
        vct.goleCount = self.goldCount;
        vct.moneyCount = self.moneyCount;
        [self.navigationController pushViewController:vct animated:YES];
    }
   
    else{
        UIViewController *vct = [[class alloc] init];
        [self.navigationController pushViewController:vct animated:YES];
    }
}

- (THPersonTableViewHeaderView *)headerView {
    static dispatch_once_t onceToken;
    static THPersonTableViewHeaderView *v = nil;
    _dispatch_once(&onceToken, ^{
        v = [THPersonTableViewHeaderView createViewFromNib];
        v.size = (CGSize){DV_W, kTHPersonTableViewHeaderHeight};
        [RACObserve(self, vipInfo) subscribeNext:^(NSDictionary *info) {
            NSInteger vipInfoTag = [[info safeObjectForKey:@"grade"] integerValue];
            if (vipInfoTag == 2) {
                NSString *validDay = [NSString stringWithFormat:@"%@",[info safeObjectForKey:@"day_num"]];
                [v.vipInfoButton setBackgroundImage:[UIImage imageNamed:@"y_th_vip"] forState:UIControlStateNormal];
                NSString *prefix = @"还剩";
                [v.vipInfoButton setTitle:[[prefix add:validDay] add:@"天"] forState:UIControlStateNormal];
            }else {
                [v.vipInfoButton setBackgroundImage:[UIImage imageNamed:@"n_th_vip"] forState:UIControlStateNormal];
                [v.vipInfoButton setTitle:@"  我要成为VIP >" forState:UIControlStateNormal];
            }
        }];
        
        RAC(v.usernameLabel, text) = RACObserve(self, username);
        [[RACObserve(self, avatarIcon) map:^id(NSString *value) {
            return [value addHTTPHeadPrefix];
        }] subscribeNext:^(NSString *x) {
            [v.avatarIcon lhy_loadImageUrlStr:x placeHolderImageName:@"th_avatar" radius:v.avatarIcon.width];
        }];
        
#pragma mark - 跳转我的详情
        UITapGestureRecognizer *gest = [UITapGestureRecognizer new];
        @weakify(self);
        [[gest rac_gestureSignal] subscribeNext:^(id x) {
            @strongify(self);
            [self pushToDetailVC];
        }];
        v.usernameLabel.userInteractionEnabled = YES;
        [v.usernameLabel addGestureRecognizer:gest];
        
        UITapGestureRecognizer *gest1 = [UITapGestureRecognizer new];
        [[gest1 rac_gestureSignal] subscribeNext:^(id x) {
            @strongify(self);
            [self pushToDetailVC];
        }];
        
        v.avatarIcon.userInteractionEnabled = YES;
        [v.avatarIcon addGestureRecognizer:gest1];
        
    });
    return v;
}

- (void)pushToDetailVC{
    THMyInfoViewController *vc = [THMyInfoViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

- (UITableView *)tableView {
    if (!_tableView ) {
        _tableView = [UITableView new];
        _tableView.backgroundColor = kHighLigtColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableHeaderView = self.headerView;
        [_headerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(_tableView);
            make.height.equalTo(@(kTHPersonTableViewHeaderHeight));
        }];
        _tableView.tableFooterView = [UIView new];
        _tableView.backgroundColor = MYCOLOR(238, 238, 238);
    }
    return _tableView;
}


/**
 头部信息
 */
- (void )getInfo{
    NSString *username = [YJUserDefaultTool readUserName];
    NSDictionary *params = @{@"username": username};
    params = [Helper actionType:@"get_my_userinfo" params:params];
    @weakify(self);
    [YJBNetworking postWithPathType:RequestPathTypeTuHaoUserInfo params:params success:^(NSDictionary * _Nullable result) {
        @strongify(self);
        NSDictionary *info = [result safeObjectForKey:@"return"][@"data"];
        self.vipInfo = info;
        self.username = [info safeObjectForKey:@"username"];
        self.avatarIcon = [info safeObjectForKey:@"user_image"];
        self.goldCount = [info safeObjectForKey:@"totalgold"];
        self.moneyCount = [info safeObjectForKey:@"money"];
    } failure:^(NSString * _Nullable error) {
        @strongify(self);
        MBProgressHUD *hud = [MBProgressHUD showMessage:error toView:self.view];
        [hud hide:YES afterDelay:1.0];
    }];
}


@end
